import _ from 'lodash'
import { MaterialApi } from '~/api/MaterialApi'

export class MaterialModel {
  public id: number
  public name: string

  /**
   * 曾经被设计成搜索时可以使用的简写但是对手机使用而言，这个设计其实没什么必要。
   * 不使用键盘的时候，切换成英文输入法实际上更麻烦。
   */
  // public alias: string

  public unit: string
  public unitPrice: number

  public specification: string // 商品的规格
  public comment: string // 商品的备注
  public takenOff: boolean // 商品是否被下架
  public group: string // 商品的分组

  public constructor() {
    this.id = 0
    this.name = ''
    // this.alias = ''
    this.unit = ''
    this.unitPrice = 0

    this.specification = ''
    this.comment = ''
    this.takenOff = false
    this.group = ''
  }

  static async fromId(id: number): Promise<MaterialModel> {
    const materials = await MaterialApi.getAll()
    const material = materials.find(x => x.id === id)
    if (!material) {
      throw new Error(`MaterialModel.fromId(id: ${id}): no such material`)
    }
    return material
  }

  public get fullName(): string {
    return `${this.name}(${this.specification})`
  }

  public getFullName(): string {
    return `${this.name}(${this.specification})`
  }

  static fromObj(obj: any): MaterialModel {
    const material = new MaterialModel()
    material.id = obj.id
    material.name = obj.name
    material.unit = obj.unit
    material.unitPrice = obj.unitPrice
    material.specification = obj.specification
    material.comment = obj.comment
    material.takenOff = obj.takenOff
    material.group = obj.group
    return material
  }
}
